<template>
  <div>
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
    <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="经办人" prop="personId">
            <el-select v-model="formData.personId" placeholder="请选择" filterable :disabled="formData.isDisabled">
        <el-option
            v-for="item in personList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
        />
      </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="部门编码" prop="deptId">
            <el-tree-select
              v-model="formData.deptId"
              :data="deptList"
              :props="defaultProps"
              check-strictly
              node-key="id" 
              placeholder="请选择部门"
              filterable 
              :disabled="formData.isDisabled"
            />
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="仓库编码" prop="warehouseId">
            <el-select v-model="formData.warehouseId" placeholder="请选择" filterable :disabled="formData.isDisabled">
              <el-option
                  v-for="item in warehouseList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
              />
            </el-select>      
          </el-form-item>
        </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col :span="8">

          <el-form-item label="流水号" prop="code">
        <el-input v-model="formData.code" placeholder="自动生成" :disabled="true"/>
      </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="盘点日期" prop="ddate">
        <el-date-picker
          v-model="formData.ddate"
          type="date"
          value-format="x"
          placeholder="选择盘点日期"
          style="width: 100%;"
          :disabled="formData.isDisabled"
        />
      </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="备注" prop="cmemo">
        <el-input v-model="formData.cmemo" placeholder="请输入备注" :disabled="formData.isDisabled" />
      </el-form-item>
        </el-col>

    </el-row>

     
    </el-form>
    <!-- 子表的表单 -->
    <el-tabs v-model="subTabsName">
      <el-tab-pane label="盘点单子表" name="checkvouchs">
        <CheckvouchsForm ref="checkvouchsFormRef" :pid="formData.id" :isDisabled="formData.isDisabled" :warehouseId="formData.warehouseId"/>
      </el-tab-pane>
    </el-tabs>
    <div class="footer">
      <el-button @click="submitForm" type="primary" :disabled="formData.isDisabled" :isDisabled="formData.isDisabled">确 定</el-button>
      <el-button @click="goBack">取 消</el-button>
    </div>
  </div>
</template>
<script setup lang="ts">
import { CheckvouchApi, CheckvouchVO } from '@/api/wms/checkvouch'
import CheckvouchsForm from './components/CheckvouchsForm.vue'
import { useRoute, useRouter } from 'vue-router';
import { ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { PersonApi, PersonVO } from '@/api/wms/person'
import { WarehouseApi, WarehouseVO } from '@/api/wms/warehouse'
import { defaultProps, handleTree } from '@/utils/tree';
import { getSimpleDeptList } from '@/api/system/dept';
import { LocationApi, LocationVO } from '@/api/wms/location'
import { useTagsViewStore } from '@/store/modules/tagsView'
/** 盘点 表单 */
defineOptions({ name: 'checkvouchFormCreate' })
const { push, currentRoute } = useRouter()
const { delView } = useTagsViewStore() // 视图操作
const { t } = useI18n() // 国际化
const route = useRoute();
const router = useRouter();
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  code: undefined,
  warehouseId: undefined,
  deptId: undefined,
  personId: undefined,
  ddate: new Date().getTime(),
  cmemo: undefined,
  createBy: undefined,
  updateBy: undefined,
  isDisabled:false,
  locationId:undefined
})
const formRules = reactive({
  personId: [{ required: true, message: '业务员不能为空', trigger: 'blur' }],
  deptId: [{ required: true, message: '部门不能为空', trigger: 'blur' }],
  warehouseId: [{ required: true, message: '仓库不能为空', trigger: 'blur' }],
  locationId: [{ required: true, message: '批号不能为空', trigger: 'blur' }],
  ddate: [{ required: true, message: '盘点日期不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref
const personList = ref([] as PersonVO[]) // 
const deptList = ref<Tree[]>([]) // 树形结构
const warehouseList = ref([] as WarehouseVO[]) // 
const locationList = ref<LocationVO[]>([]) // 列表的数据

/** 子表的表单 */
const subTabsName = ref('checkvouchs')
const checkvouchsFormRef = ref()

onMounted(async () => {
    //加载人员数据
    personList.value = await PersonApi.getPersonSimpleList()
  //加载部门树
  deptList.value = handleTree(await getSimpleDeptList())
  //加载供应商
  warehouseList.value= await WarehouseApi.getWarehouseSimpleList()

  locationList.value=await LocationApi.getLocationSimpleList()
  initFormData(route.query.id ? String(route.query.id) : undefined);
});

/** 初始化表单数据 */
const initFormData = async (id?: any) => {
  if (id) {  
    formLoading.value = true;
    try {
      if(id!='undefined'){
        formData.value = await CheckvouchApi.getCheckvouch(id);
      }
    
      if(route.query.type=='select')
      {
        formData.value.isDisabled = true; // 查看时不可以编辑
      formType.value = 'select';
      }else if(route.query.type=='update'){
        formData.value.isDisabled = false; // 修改时可以编辑
      formType.value = 'update';
      }else if(route.query.type=='create'){
      // formData.value.isDisabled = false; // 新增时可以编辑
      formType.value = 'create';
      resetForm();
      }else{
        formData.value.isDisabled = true; // 查看时不可以编辑
      formType.value = 'select';
      }
    } finally {
      formLoading.value = false;
    }
  } else {
    // formData.value.isDisabled = false; // 创建时可以编辑
    resetForm();
    formType.value = 'create';
  }
};

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 校验子表单
  try {
    await checkvouchsFormRef.value.validate()
  } catch (e) {
    subTabsName.value = 'checkvouchs'
    return
  }
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as CheckvouchVO
    // 拼接子表的数据
    data.checkvouchss = checkvouchsFormRef.value.getData()
    if (formType.value === 'create') {
      await CheckvouchApi.createCheckvouch(data)
      ElMessage.success(t('common.createSuccess'))
    } else {
      await CheckvouchApi.updateCheckvouch(data)
      ElMessage.success(t('common.updateSuccess'))
    }
    delView(unref(currentRoute))
    // 发送操作成功的事件
    push('/inventory/checkvouch');
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    code: undefined,
    cpersoncode: undefined,
    cdepcode: undefined,
    cwhcode: undefined,
    ddate: new Date().getTime(),
    cmemo: undefined,
    createBy: undefined,
    updateBy: undefined,
  }
  formRef.value?.resetFields()
}

/** 返回上一页 */
const goBack = () => {
  delView(unref(currentRoute))
  push('/inventory/checkvouch');
  

};
</script>

<style scoped>
.footer {
  margin-top: 20px;
  text-align: right;
}
</style>